﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Guline.Web.JXAccount.Models;
using System.Web.Security;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using Guline.Web.JXAuth;
using Guline.Web.JXAccount.wsjxLib;
namespace Guline.Web.JXAccount.Controllers
{
    public class HomeController : BaseController
    {
        private Models.Caderer Cardmn;
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Panel");
            }
            ViewBag.msg = wsjxclient.HelloWorld();
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }
        public ActionResult Register()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Panel");
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult Register(Models.RegisterUser model)
        {
            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                        model.pass1 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass1, "MD5");
                        model.pass2 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass2, "MD5");
                    }
                    if (wsjxclient.Register(this.gulinekey, model.Username, model.pass1, model.pass2, model.Email, model.ask, model.answer, model.Phone))
                    {
                        return View("RegisterSuccess", model);
                    }
                    else
                    {
                        ModelState.AddModelError("MaBVKhongDung", "Không thể thêm tài khoản, đã có lỗi xảy ra");
                    }
                }
                else
                {
                    ModelState.AddModelError("MaBVKhongDung", "Mã bảo vệ không đúng");
                }
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name", model.ask);
            return View(model);
        }
        public ActionResult Login(string ReturnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Panel");
            }
            ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }
        [HttpPost]
        public ActionResult Login(Models.User model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_useMD5)
                {
                    model.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5");
                }
                bool result = wsjxclient.Login(this.gulinekey, model.Username, model.Password);
                if (result)
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    if (!string.IsNullOrEmpty(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    return RedirectToAction("Panel");
                }
                else
                {
                    ModelState.AddModelError("LoginNotFound", "Tài khoản hoặc mật khẩu không đúng.");
                }
            }
            ViewBag.ReturnUrl = ReturnUrl;
            return View(model);
        }
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [Authorize]
        public ActionResult Panel()
        {

            return View();
        }
        public CaptchaImageResult ShowCaptchaImage()
        {
            return new CaptchaImageResult();
        }
        public ActionResult CheckUser(string username)
        {

            return Json(new { result = wsjxclient.Checkuser(this.gulinekey, username) });
        }
        public ActionResult CheckEmail(string email)
        {

            return Json(new { result = wsjxclient.CheckEmail(this.gulinekey, email) });
        }
        public ActionResult ChangePassword()
        {
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult ChangePassword(Models.UserChangPass model)
        {
            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                        model.pass1 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass1, "MD5");
                        model.passnew = FormsAuthentication.HashPasswordForStoringInConfigFile(model.passnew, "MD5");
                    }
                    if (wsjxclient.Login(this.gulinekey, User.Identity.Name, model.pass1))
                    {
                        bool result = wsjxclient.changpass1(this.gulinekey, User.Identity.Name, model.passnew, model.ask, model.answer);
                        if (result)
                        {
                            return View("ChangePasswordSuccess");
                        }
                        else
                        {
                            ModelState.AddModelError("MaBVKhonDung", "Câu hỏi hoặc câu trả lời không đúng.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("MaBVKhonDung", "Mật khẩu hiện tại không đúng.");
                    }
                }
                else
                {
                    ModelState.AddModelError("MaBVKhonDung", "Mã bảo vệ không đúng.");
                }
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name", model.ask);
            return View(model);
        }
        [Authorize]
        public ActionResult NapThe()
        {
            List<Mang> loaithe = new List<Mang>();
            loaithe.Add(new Mang() { ID = "VIETTEL", Name = "Viettel" });
            //loaithe.Add("GATE", "Gate");
            loaithe.Add(new Mang() { ID = "GATE", Name = "Gate" });
            //VMS
            loaithe.Add(new Mang() { ID = "VMS", Name = "Mobifone" });
            loaithe.Add(new Mang() { ID = "VNP", Name = "Vinaphone" });
            ViewBag.Type = new SelectList(loaithe, "ID", "Name");
            return View();

        }
        [Authorize]
        [HttpPost]
        public ActionResult NapThe(Models.Card model)
        {
            if (ModelState.IsValid)
            {
                RequestInfo info = new RequestInfo();


                //Nhà mạng
                info.CardType = model.Type;
                info.Pincard = model.PIN;

                //Mã đơn hàng
                info.Refcode = (new Random().Next(0, 10000)).ToString();
                info.SerialCard = model.Serial;

                ResponseInfo resutl = NLCardLib.CardChage(info);

                String html = "";

                if (resutl.Errorcode.Equals("00"))
                {
                    //html += "-" + resutl.Message + "\n";
                    //html += "-Số tiền nạp : " + resutl.Card_amount + "đ\n";
                    //html += "-Mã giao dịch : " + resutl.TransactionID + "\n";
                    //html += "-Mã đơn hàng : " + resutl.Refcode + "\n";
                   

                    Cardmn = new Models.Caderer(Server.MapPath("~/bin/GulineJX.pop"));
                    Models.CardCharge card = Cardmn.Search(resutl.Card_amount);
                    //Models.CardCharge card = Cardmn.Search("10000");
                    //Models.CardCharge card = Cardmn.Search("10000");
                    int xu = 0;
                    if (card != null)
                    {
                        xu = int.Parse(card.Xu);
                    }
                    else
                    {
                        int amount = int.Parse(resutl.Card_amount);
                        
                        switch (amount)
                        {
                            case 10000:
                                xu = 1;
                                break;
                            case 20000:
                                xu = 3;
                                break;
                            case 30000:
                                xu = 4;
                                break;
                            case 50000:
                                xu = 8;
                                break;
                            case 100000:
                                xu = 16;
                                break;
                            case 200000:
                                xu = 31;
                                break;
                            case 300000:
                                xu = 46;
                                break;
                            case 500000:
                                xu = 80;
                                break;
                            default: xu = 0; break;
                        }
                    }
                    
                    if (wsjxclient.CongKNB(this.gulinekey, User.Identity.Name, xu) == 0)
                    {
                        TextWriter tsw1 = new StreamWriter(Server.MapPath("~/CardCharge/member/failed-" + User.Identity.Name + ".pop"), true);
                        tsw1.WriteLine(User.Identity.Name + " Không cộng được kim nguyên bảo " + DateTime.Now.ToString() + "- KNB:" + xu + "- Thẻ:  " + model.Type + "- Mã thẻ: " + model.PIN + "-Serial:" + model.Serial);
                        tsw1.Close();

                        TextWriter tsw = new StreamWriter(Server.MapPath("~/CardCharge/failed-" + DateTime.Now.ToString("yyyy-MM-dd") + ".pop"), true);
                        tsw.WriteLine(User.Identity.Name + " Không thêm KNB được " + DateTime.Now.ToString() + "- KNB:" + xu + "- Thẻ: " + model.Type + "- Mã thẻ: " + model.PIN + "-Serial:" + model.Serial);
                        tsw.Close();
                        ModelState.AddModelError("", "Không nạp được thêm, vui lòng liên hệ admin để được giải quyết, xin cám ơn.");
                    }
                    else
                    {
                        TextWriter tsw1 = new StreamWriter(Server.MapPath("~/CardCharge/member/true-"+User.Identity.Name + ".pop"), true);
                        tsw1.WriteLine(User.Identity.Name + " Nạp thẻ đúng lúc " + DateTime.Now.ToString() + "-" + resutl.Card_amount + " KNB:" + xu + "- Thẻ:  " + model.Type + "- Mã thẻ: " + model.PIN + "-Serial:" + model.Serial);
                        tsw1.Close();

                        TextWriter tsw = new StreamWriter(Server.MapPath("~/CardCharge/true-" + DateTime.Now.ToString("yyyy-MM-dd") + ".pop"), true);
                        tsw.WriteLine(User.Identity.Name + " Nạp thẻ đúng lúc " + DateTime.Now.ToString() + "-" + resutl.Card_amount + " KNB:" + xu + "- Thẻ:  " + model.Type + "- Mã thẻ: " + model.PIN + "-Serial:" + model.Serial);
                        tsw.Close();
                        return RedirectToAction("NapTheSuccess");
                    }

                }
                else
                {
                    TextWriter tsw1 = new StreamWriter(Server.MapPath("~/CardCharge/member/false-" + User.Identity.Name + ".pop"), true);
                    tsw1.WriteLine(User.Identity.Name + " Không cộng được kim nguyên bảo " + DateTime.Now.ToString() + "- Thẻ:  " + model.Type + "- Mã thẻ: " + model.PIN + "-Serial:" + model.Serial);
                    tsw1.Close();

                    TextWriter tsw = new StreamWriter(Server.MapPath("~/CardCharge/false-" + DateTime.Now.ToString("yyyy-MM-dd") + ".pop"), true);
                    tsw.WriteLine(User.Identity.Name + " Nạp thẻ sai lúc " + DateTime.Now.ToString() + "Thẻ: "+model.Type+"- Mã thẻ:" + model.PIN + "-Serial:" + model.Serial);
                    tsw.Close();
                    html += "-Nạp thẻ không thành công\n";
                    html += "-" + resutl.Message + "\n";
                }
                ModelState.AddModelError("", html);
            }
            List<Mang> loaithe = new List<Mang>();
            loaithe.Add(new Mang() { ID = "VIETTEL", Name = "Viettel" });
            //loaithe.Add("GATE", "Gate");
            loaithe.Add(new Mang() { ID = "GATE", Name = "Gate" });
            //VMS
            loaithe.Add(new Mang() { ID = "VMS", Name = "Mobifone" });
            loaithe.Add(new Mang() { ID = "VNP", Name = "Vinaphone" });
            ViewBag.Type = new SelectList(loaithe, "ID", "Name", model.Type);
            return View(model);
        }
        public ActionResult NapTheSuccess ()
        {
            return View();
        }
        [Authorize]
        public ActionResult XuInfo()
        {

            var habitus = wsjxclient.getAccountInfo(this.gulinekey, User.Identity.Name);
            return PartialView(habitus);
        }
        [Authorize]
        public ActionResult ChangePass2()
        {

            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangePass2(Models.UserChangePass2 model)
        {
            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                        model.pass2 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass2, "MD5");
                        model.pass2new = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass2new, "MD5");
                    }
                    if (wsjxclient.changpass2(this.gulinekey, User.Identity.Name, model.pass2, model.pass2new))
                    {
                        return RedirectToAction("ChangPass2Success");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu cấp 2 hiện tại không đúng!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Mã bảo vệ không đúng!");
                }
            }
            return View();
        }
        [Authorize]
        public ActionResult ChangPass2Success()
        {
            return View();
        }
        //ChangeEmail
        [Authorize]
        public ActionResult ChangeEmail()
        {
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangeEmail(Models.ChangeEmail model)
        {

            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                        model.pass2 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass2, "MD5");

                    }
                    if (wsjxclient.change_email(this.gulinekey, User.Identity.Name, model.pass2, model.emailnew, model.ask, model.answer))
                    {
                        return RedirectToAction("ChangEmailSuccess");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu cấp 2 hoặc câu hỏi & trả lời không đúng!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Mã bảo vệ không đúng!");
                }
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        //ChangEmailSuccess
        [Authorize]
        public ActionResult ChangEmailSuccess()
        {
            return View();
        }
        //ChangeQuest
        public ActionResult ChangeQuest()
        {
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangeQuest(Models.ChangeEmail model)
        {

            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                        model.pass2 = FormsAuthentication.HashPasswordForStoringInConfigFile(model.pass2, "MD5");

                    }
                    if (wsjxclient.change_quest(this.gulinekey, User.Identity.Name, model.pass2, model.emailnew, model.ask, model.answer))
                    {
                        return RedirectToAction("ChangeQuestSuccess");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu cấp 2 hoặc email không đúng!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Mã bảo vệ không đúng!");
                }
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        public ActionResult ChangeQuestSuccess()
        {
            return View();
        }

        public ActionResult LostPassword()
        {
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult LostPassword(Models.LostPassword model)
        {
            if (ModelState.IsValid)
            {
                if (Session["captchastring"].ToString().ToUpper() == model.Captcha.ToUpper())
                {
                    if (_useMD5)
                    {
                       
                        model.passnew = FormsAuthentication.HashPasswordForStoringInConfigFile(model.passnew, "MD5");
                    }
                    if (wsjxclient.Checkuser(this.gulinekey,model.Username))
                    {
                        bool result = wsjxclient.changpass1(this.gulinekey, model.Username, model.passnew, model.ask, model.answer);
                        if (result)
                        {
                            return View("LostPasswordSuccess");
                        }
                        else
                        {
                            ModelState.AddModelError("MaBVKhonDung", "Câu hỏi hoặc câu trả lời không đúng.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tài khoản không tồn tại.");
                    }
                }
                else
                {
                    ModelState.AddModelError("MaBVKhonDung", "Mã bảo vệ không đúng.");
                }
            }
            ViewBag.ask = new SelectList(this.listQuest, "ID", "Name",model.ask);
            return View(model);
        }
        public ActionResult LostPasswordSuccess()
        {
            return View();
        }
    }
}
